package com.hhs.storage.controller;


import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hhs.storage.bean.*;
import com.hhs.storage.service.BaseUserService;
import com.hhs.storage.service.XmFileShareService;
import com.hhs.storage.service.XmPptService;
import com.hhs.storage.util.FileUpload;
import com.hhs.storage.util.NumberUtil;
import com.hhs.storage.util.StringUtil;
import com.hhs.storage.util.SysUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author chx
 * @since 2024-10-14
 */
@RestController
@RequestMapping("xmppt")
@Slf4j
public class XmPptController {
    @Resource
    private XmPptService xmpptService;
    @Resource
    private HttpServletRequest request;
    @Resource
    private HttpServletResponse response;
    @Resource
    private XmFileShareService xmFileShareService;
    @Resource
    private BaseUserService baseUserService;

    @Value("${upload.folderName}")
    private String folderName;

    @RequestMapping("edit")
    public Map<String,Object> edit(XmPpt xmppt){
        if(StringUtil.iszNull(xmppt.getId())){
            xmppt.setCreateTime(LocalDateTime.now());
        }
        QueryWrapper qw=new QueryWrapper();
        qw.eq("ppt_id", xmppt.getPptId());
        List list = xmpptService.list(qw);
        if(list.size()==0){
            xmpptService.save(xmppt);
            return ResponseInfo.success();
        }
        return ResponseInfo.error("此文件本地已经保存过！");
    }
    @RequestMapping("table")
    public Map<String,Object> table(InputParam inputParam){
        if(StringUtil.iszNull(inputParam.getUserId())){
            return ResponseInfo.error("没有用户ID,参数错误");
        }
        QueryWrapper qw=new QueryWrapper();
        qw.eq("user_id", inputParam.getUserId());
        if(!StringUtil.iszNull(inputParam.getName())){
            qw.like("ppt_name", inputParam.getName());
        }
        if(inputParam.getType()!=null&&inputParam.getType()!=-1){
            qw.eq("type", inputParam.getType());
        }
        Page<XmPpt> mp = xmpptService.page(new Page(inputParam.getPage(), inputParam.getSize()),qw);
        Map<String,Object> map=new HashMap<>();
        map.put("code",1);
        map.put("rows",mp.getRecords());
        map.put("total",mp.getTotal());
        return map;
    }

    /**
     * 列表他人共享的文件
     * @param inputParam
     * @return
     */
    @RequestMapping("tableOther")
    public Map<String,Object> tableOther(InputParam inputParam){
        Page<XmPpt> page= xmpptService.pageOther(inputParam);
        Map<String,Object> map=new HashMap<>();
        map.put("code",1);
        map.put("rows",page.getRecords());
        map.put("total",page.getTotal());
        return map;
    }

    @RequestMapping("dele")
    public Map<String,Object> dele(XmPpt xmppt){
        if(StringUtil.iszNull(xmppt.getId())){
            return ResponseInfo.error("没有id,参数错误");
        }
        xmpptService.removeById(xmppt.getId());
        return ResponseInfo.success();
    }

    @RequestMapping("saveanswer")
    public Map<String,Object> saveanswer(InputParam inputParam){
        XmPpt pptId = xmpptService.getOne(new QueryWrapper<XmPpt>().eq("ppt_id", inputParam.getPptId()));
        if(pptId!=null){
            return ResponseInfo.error("文件已经保存过了");
        }
        JSONArray jsonArray=JSONArray.parseArray(inputParam.getContent());
        StringBuffer sb=new StringBuffer();
        for(int i=0;i<jsonArray.size();i++){
            String replace = StringUtil.replace(jsonArray.get(i).toString(), "<br>", "\n");
            if(i%2==0){
                sb.append("我: "+replace+"\n\n\n");
            }else{
                sb.append("小蜜助教: "+replace+"\n\n\n");
            }
        }
        //上传文件
        String path = FileUpload.writeUploadFileString(sb.toString(), folderName, "");
        XmPpt xmPpt=new XmPpt();
        xmPpt.setUserId(SysUtil.getLoginUserId(request));
        xmPpt.setCreateTime(LocalDateTime.now());
        xmPpt.setPptId(inputParam.getPptId());
        xmPpt.setPptName(inputParam.getName());
        xmPpt.setXmPptPath(path);
        xmPpt.setType(inputParam.getType());
        xmpptService.save(xmPpt);
        return ResponseInfo.success(path);
    }

    @RequestMapping("saveFile")
    public Map<String,Object> saveFile(XmPpt xmPpt){
        xmPpt.setUserId(SysUtil.getLoginUserId(request));
        xmPpt.setCreateTime(LocalDateTime.now());
        xmpptService.save(xmPpt);
        return ResponseInfo.success();
    }
    @RequestMapping("saveoutline")
    public Map<String,Object> saveoutline(InputParam inputParam){
//        XmPpt pptId = xmpptService.getOne(new QueryWrapper<XmPpt>().eq("ppt_id", inputParam.getPptId()));
//        if(pptId!=null){
//            return ResponseInfo.error("文件已经保存过了");
//        }
        StringBuffer sb=new StringBuffer();
        sb.append(inputParam.getContent());
        //上传文件
        String path = FileUpload.writeUploadFileString(sb.toString(), folderName, "");
        XmPpt xmPpt=new XmPpt();
        xmPpt.setUserId(SysUtil.getLoginUserId(request));
        xmPpt.setCreateTime(LocalDateTime.now());
        xmPpt.setPptId(inputParam.getPptId());
        xmPpt.setPptName(inputParam.getName());
        xmPpt.setXmPptPath(path);
        xmPpt.setType(inputParam.getType());
        xmpptService.save(xmPpt);
        return ResponseInfo.success(path);
    }
    /**
     * ppt下载文件
     * @param id
     * @return
     */
    @RequestMapping("downLoad")
    @ResponseBody
    public void downLoad(String id) throws IOException {
        XmPpt obj=xmpptService.getById(id);
        //把服务器中文件读取到内存中
        //把服务器中文件读取到内存中
        FileInputStream fis=null;
        ServletOutputStream os=null;
        try{
            File f=new File(folderName,obj.getXmPptPath());
            fis = new FileInputStream(f);
            //设置下载的类型
            response.setHeader("content-disposition","attachment;fileName="+ URLEncoder.encode(obj.getPptName(),"UTF-8"));
            response.addHeader("Content-Length", "" + f.length());
            response.setContentType("application/octet-stream");
            //获取输出流
            os = response.getOutputStream();
            //复制
            IOUtils.copy(fis,os);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(fis!=null){
                //关闭资源
                fis.close();
            }
            if(os!=null){
                os.close();
            }
        }
    }
    /**
     * 文件分享给班级
     * @param inputParam
     * @return
     */
    @RequestMapping("shareFile")
    public Map<String,Object> shareFile(InputParam inputParam) throws IOException {
        QueryWrapper qw=new QueryWrapper();
        if(StringUtil.iszNull(inputParam.getType())||StringUtil.iszNull(inputParam.getId())){
            return ResponseInfo.error("参数错误");
        }
        qw.eq("type", inputParam.getType());
        qw.eq("file_id", inputParam.getId());
        xmFileShareService.remove(qw);
        if(!StringUtil.iszNull(inputParam.getIds())){
            String[] ids=inputParam.getIds().split(",");
            for(String cid:ids){
                XmFileShare xfs=new XmFileShare();
                xfs.setType(inputParam.getType());
                xfs.setTargetId(cid);
                xfs.setFileId(inputParam.getId());
                xmFileShareService.save(xfs);
            }
        }
        return ResponseInfo.success();
    }

    /**
     * 得到文件分享的状态
     * @param inputParam
     * @return
     */
    @RequestMapping("getShareStatus")
    public Map<String,Object> getShareStatus(InputParam inputParam) throws IOException {
        QueryWrapper qw=new QueryWrapper();
        if(StringUtil.iszNull(inputParam.getType())||StringUtil.iszNull(inputParam.getId())){
            return ResponseInfo.error("参数错误");
        }
        qw.eq("type", inputParam.getType());
        qw.eq("file_id", inputParam.getId());
        List list = xmFileShareService.list(qw);
        return ResponseInfo.success(list);
    }

    /**
     * 设置文件共享属性
     * @param inputParam
     * @return
     */
    @RequestMapping("setShareFile")
    public Map<String,Object> setShareFile(InputParam inputParam) throws IOException {
        QueryWrapper qw=new QueryWrapper();
        if(StringUtil.iszNull(inputParam.getType())||StringUtil.iszNull(inputParam.getId())){
            return ResponseInfo.error("参数错误");
        }
        qw.eq("type", inputParam.getType());
        qw.eq("file_id", inputParam.getId());
        xmFileShareService.remove(qw);
        String getType=inputParam.getIds().split(",")[0];
        if(!"0".equals(getType)){
            Integer cost=inputParam.getCost();
                XmFileShare xfs=new XmFileShare();
                xfs.setType(inputParam.getType());
                xfs.setFileId(inputParam.getId());
                xfs.setGetType(NumberUtil.toIntCase(getType));
                xfs.setCost(cost);
                xmFileShareService.save(xfs);
        }
        return ResponseInfo.success();
    }

}

